from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime

from ..core.database import get_db
from ..models.user import User
from ..models.store import Store
from ..models.product import Product
from ..models.group_buy_order import GroupBuyOrder
from ..models.user_order import UserOrder
from ..models.stored_value_card import StoredValueCard
from ..models.consumption_record import ConsumptionRecord

router = APIRouter(prefix="/api/user", tags=["user"])

# 响应模型
class OrderResponse(BaseModel):
    id: int
    store_name: str
    store_logo: str
    product_name: str
    product_image: str
    shares: int
    total_amount: float
    status: str
    group_buy_progress: str
    group_buy_status: int
    created_at: datetime

class StoredValueCardResponse(BaseModel):
    id: int
    store_name: str
    store_logo: str
    card_number: str
    original_amount: float
    current_amount: float
    status: str
    valid_until: datetime

class ConsumptionRecordResponse(BaseModel):
    id: int
    store_name: str
    amount: float
    description: str
    consumed_at: datetime

class UserProfileResponse(BaseModel):
    id: int
    nickname: str
    avatar_url: str
    phone: str
    created_at: datetime

@router.get("/orders", response_model=List[OrderResponse])
async def get_user_orders(
    phone: str,
    status: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """获取用户订单列表"""
    try:
        # 根据手机号查找用户
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 获取用户的订单
        orders = db.query(UserOrder).filter(UserOrder.user_id == user.id).all()
        
        result = []
        for order in orders:
            # 获取商品信息
            product = db.query(Product).filter(Product.id == order.product_id).first()
            if not product:
                continue
                
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == product.store_id).first()
            if not store:
                continue
            
            # 获取拼购信息
            group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == order.group_buy_order_id).first()
            
            # 映射支付状态
            status_map = {
                0: 'pending',    # 待支付
                1: 'using',      # 已支付（待使用）
                2: 'refunded'    # 已退款
            }
            
            # 如果拼购已完成，状态改为completed
            if group_buy and group_buy.status == 2:
                order_status = 'completed'
            else:
                order_status = status_map.get(order.payment_status, 'pending')
            
            # 如果有状态筛选，跳过不匹配的订单
            if status and order_status != status:
                continue
            
            # 安全地获取拼购进度
            group_buy_progress = "0/0"
            group_buy_status = 0
            if group_buy:
                group_buy_progress = f"{group_buy.sold_shares}/{group_buy.total_shares}"
                group_buy_status = group_buy.status
            
            result.append(OrderResponse(
                id=order.id,
                store_name=store.name,
                store_logo=store.logo_url,
                product_name=product.name,
                product_image=product.images[0] if isinstance(product.images, list) and product.images and len(product.images) > 0 else (product.images.split(',')[0] if product.images and ',' in product.images else product.images),
                shares=order.shares,
                total_amount=float(order.total_amount),
                status=order_status,
                group_buy_progress=group_buy_progress,
                group_buy_status=group_buy_status,
                created_at=order.created_at
            ))
        
        # 按下单时间倒序排列
        result.sort(key=lambda x: x.created_at, reverse=True)
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"获取订单失败: {str(e)}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"获取订单失败: {str(e)}")

@router.get("/stored-value-cards", response_model=List[StoredValueCardResponse])
async def get_user_stored_value_cards(
    phone: str,
    db: Session = Depends(get_db)
):
    """获取用户储值卡列表"""
    try:
        # 根据手机号查找用户
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 获取用户的储值卡
        cards = db.query(StoredValueCard).filter(StoredValueCard.user_id == user.id).all()
        
        result = []
        for card in cards:
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == card.store_id).first()
            if not store:
                continue
            
            result.append(StoredValueCardResponse(
                id=card.id,
                store_name=store.name,
                store_logo=store.logo_url,
                card_number=card.card_number,
                original_amount=float(card.original_amount),
                current_amount=float(card.current_amount),
                status=str(card.status),  # 1:正常 0:已用完
                valid_until=card.valid_until
            ))
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取储值卡失败: {str(e)}")

@router.get("/consumption-records", response_model=List[ConsumptionRecordResponse])
async def get_user_consumption_records(
    phone: str,
    card_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取用户消费记录"""
    try:
        # 根据手机号查找用户
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 获取用户的消费记录
        query = db.query(ConsumptionRecord).filter(ConsumptionRecord.user_id == user.id)
        
        if card_id:
            query = query.filter(ConsumptionRecord.card_id == card_id)
        
        records = query.all()
        
        result = []
        for record in records:
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == record.store_id).first()
            if not store:
                continue
            
            result.append(ConsumptionRecordResponse(
                id=record.id,
                store_name=store.name,
                amount=float(record.amount),
                description=record.description,
                consumed_at=record.consumed_at
            ))
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取消费记录失败: {str(e)}")

@router.get("/profile", response_model=UserProfileResponse)
async def get_user_profile(
    phone: str,
    db: Session = Depends(get_db)
):
    """获取用户资料"""
    try:
        # 根据手机号查找用户
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        return UserProfileResponse(
            id=user.id,
            nickname=user.nickname,
            avatar_url=user.avatar_url,
            phone=user.phone,
            created_at=user.created_at
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户资料失败: {str(e)}")

@router.get("/group-buys")
async def get_user_group_buys(
    phone: str,
    db: Session = Depends(get_db)
):
    """获取用户参与的拼购"""
    try:
        # 根据手机号查找用户
        user = db.query(User).filter(User.phone == phone).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        # 获取用户参与的拼购 - 通过user_orders表关联
        user_orders = db.query(UserOrder).filter(UserOrder.user_id == user.id).all()
        
        result = []
        for user_order in user_orders:
            # 获取拼购订单信息
            group_buy = db.query(GroupBuyOrder).filter(GroupBuyOrder.id == user_order.group_buy_order_id).first()
            if not group_buy:
                continue
                
            # 获取商品信息
            product = db.query(Product).filter(Product.id == group_buy.product_id).first()
            if not product:
                continue
                
            # 获取店铺信息
            store = db.query(Store).filter(Store.id == product.store_id).first()
            if not store:
                continue
            
            result.append({
                "id": group_buy.id,
                "store_name": store.name,
                "store_logo": store.logo_url,
                "product_name": product.name,
                "product_image": product.images[0] if isinstance(product.images, list) and product.images and len(product.images) > 0 else (product.images.split(',')[0] if product.images and ',' in product.images else product.images),
                "sold_shares": group_buy.sold_shares,
                "total_shares": group_buy.total_shares,
                "status": group_buy.status,
                "user_shares": user_order.shares,  # 用户购买的份数
                "user_amount": float(user_order.total_amount),  # 用户支付的金额
                "created_at": group_buy.created_at
            })
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取拼购记录失败: {str(e)}") 